package Classic150;

public class 单词搜索 {

    char[][] board;
    int m;
    int n;
    boolean[][] used;
    String word;
    boolean flag;
    int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    /*
        成功找到就返回，避免搜索整个解空间
     */
    public boolean exist(char[][] board, String word) {
        this.board = board;
        m = board.length;
        n = board[0].length;
        used = new boolean[m][n];
        this.word = word;
        int len = word.length();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                backTracking(i, j, len - 1);
                if (flag) return true;
            }
        }
        return false;
    }

    private void backTracking(int i, int j, int index) {
        if (index < 0) {
            flag = true;
            return;
        }
        if (i < 0 || i == m || j < 0 || j == n || used[i][j] || board[i][j] != word.charAt(index)) return;
        used[i][j] = true;
        for (int[] dir : dirs) {
            backTracking(i + dir[0], j + dir[1], index - 1);
            if (flag) return;
        }
        used[i][j] = false;
    }
}
